package com.lihuinch.future;

import com.lihuinch.MqttTest;
import org.fusesource.mqtt.client.*;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author lihuinch
 * @date 2019/1/31 9:02
 */
public class MqttSubscribeAlways {
    private final static String topicname = "test";


    public static void main(String[] args) throws Exception {
        Properties prop = new Properties();
        prop.load(MqttTest.class.getResourceAsStream("/apollo.properties"));
        String user = prop.getProperty("apollo.user");
        String password = prop.getProperty("apollo.password");
        String host = prop.getProperty("apollo.host");
        Integer port = Integer.parseInt(prop.getProperty("apollo.port"));

        MQTT mqtt = new MQTT();
        mqtt.setHost(host, port);
        mqtt.setUserName(user);
        mqtt.setPassword(password);
        mqtt.setClientId("111");


        FutureConnection connection = mqtt.futureConnection();
        connection.connect();
        int count = 0;

        System.out.println("用于接受消息");
        //while (true) {
            count++;
            // 用于接受消息，目前手机段不需要向服务端发送消息
            //主题的内容
            connection.subscribe(new Topic[]{new Topic(topicname, QoS.EXACTLY_ONCE)});
            Future<Message> receive = connection.receive();
            Message message = receive.await(3000L, TimeUnit.MILLISECONDS);
            System.out.println(new String(message.getPayload()));
            // 回应
            message.ack();

            System.out.println("MQTTFutureServer.publish Message " + "Topic Title :" + topicname + " context :" + message);

            Thread.sleep(2000);
      //  }

    }

}
